package com.spark.gaea.utils;

import com.google.common.collect.Maps;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public final class MapUtil {
	public static boolean isNotEmpty(final Map map) {
		return map != null && !map.isEmpty() && map.size() > 0;
	}

	public static <T> Map<String, Object> beanToMap(final T bean) {
		final Class<?> type = bean.getClass();
		final Map<String, Object> returnMap = Maps.newHashMap();
		try {
			final BeanInfo beanInfo = Introspector.getBeanInfo(type);
			final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (final PropertyDescriptor descriptor : propertyDescriptors) {
				final String propertyName = descriptor.getName();
				if (!propertyName.equals("class")) {
					final Method readMethod = descriptor.getReadMethod();
					final Object result = readMethod.invoke(bean);
					returnMap.put(propertyName, result);
				}
			}
		} catch (IntrospectionException e) {
			throw new RuntimeException("分析类属性失败", e);
		} catch (IllegalAccessException e2) {
			throw new RuntimeException("分析类属性失败", e2);
		} catch (InvocationTargetException e3) {
			throw new RuntimeException("分析类属性失败", e3);
		}
		return returnMap;
	}

	public static <T> T mapToBean(final Map<String, Object> paramMap, final Class<T> clazz) {
		T beanObj = null;
		try {
			beanObj = clazz.newInstance();
			String propertyName = null;
			Object propertyValue = null;
			for (final Map.Entry<String, Object> entity : paramMap.entrySet()) {
				propertyName = entity.getKey();
				propertyValue = entity.getValue();
				setProperties(beanObj, propertyName, propertyValue);
			}
		} catch (IllegalArgumentException e) {
			throw new RuntimeException("不合法或不正确的参数", e);
		} catch (IllegalAccessException e2) {
			throw new RuntimeException("实例化JavaBean失败", e2);
		} catch (Exception e3) {
			throw new RuntimeException("Map转换为Java Bean对象失败", e3);
		}
		return beanObj;
	}

	private static <T> void setProperties(final T entity, final String propertyName, final Object value)
			throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		final PropertyDescriptor pd = new PropertyDescriptor(propertyName, entity.getClass());
		final Method methodSet = pd.getWriteMethod();
		methodSet.invoke(entity, value);
	}
}
